package com.zeropoint.demo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringArrayHandler extends BaseTypeHandler<String[]> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        if(strings == null) {
            preparedStatement.setString(i, null);
            return;
        }

        StringBuilder builder = new StringBuilder();
        for(String str: strings){
            builder.append(str + ",");
        }

        if(builder.length() == 0){
            preparedStatement.setString(i, null);
            return;
        }
        builder.deleteCharAt(builder.length()-1);
        preparedStatement.setString(i, builder.toString());
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, String s) throws SQLException {

        String result = resultSet.getString(s);
        if(result!=null){
             return result.split(",");
        }else{
             return new String[0];
        }
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, int i) throws SQLException {

        String result = resultSet.getString(i);
        if(result!=null){
            return result.split(",");
        }else{
            return new String[0];
        }

    }

    @Override
    public String[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return new String[0];
    }


}
